<template>
  <div class="main-container container-fluid container-limited page-holder">
    <div class="page-title-holder">
      <h2 class="page-title">公告</h2>
    </div>
    <announcements-list :announcements.sync="announcements" />
    <div
      class="easy-container info text-center border-bottom pointer"
      @click="loadMore"
      v-loading="loading"
    >
      {{ loadingText }}
    </div>
    <release-announcement v-if="isWebAdmin" @released="releasedAnnouncement" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import AnnouncementsList from './components/announcements_list/list';
import ReleaseAnnouncement from './components/release-announcement';

export default {
  name: 'Announcements', // 公告
  components: { AnnouncementsList, ReleaseAnnouncement },
  data() {
    return {
      announcements: [],
      loading: false,
      nextPage: null,
    };
  },
  computed: {
    ...mapGetters(['isWebAdmin']),
    loadingText() {
      if (this.loading) return '加载中...';
      else if (this.nextPage) return '加载更多';
      return '没有更多了';
    },
  },
  created() {
    this.loadAnnouncements();
  },
  methods: {
    // 加载公告列表
    loadAnnouncements(page = 1) {
      this.loading = true;
      this.$api.announcements.index({ page })
        .then((res) => {
          this.announcements = this.announcements.concat(res.data);
          this.nextPage = res.kaminari.next_page;
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 加载更多
    loadMore() {
      if (this.nextPage) this.loadAnnouncements(this.nextPage);
    },
    // 发布了公告
    releasedAnnouncement(announcement) {
      this.announcements.unshift(announcement);
      this.backtop();
    },
  },
};
</script>

<style></style>
